package fieldmaps.files;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

import fieldmaps.types.MapInfo;

public class BilHeaderParser {

	public static MapInfo readHeader (String filename) throws IOException {

		FileInputStream file = new FileInputStream(filename);
		InputStreamReader stream = new InputStreamReader(file);
		BufferedReader reader = new BufferedReader(stream);
		String line = null;

		Map<String, String> properties = new HashMap<String, String>();

		while ((line = reader.readLine()) != null) {
			String[] values = line.split(" +");
			if(values.length > 1) {
				properties.put(values[0], values[1]);
			}
		}

		System.out.println("Parsing the Header...");

		MapInfo mapInfo = new MapInfo();

		mapInfo.setByteOrder (properties.get("BYTEORDER").charAt(0));
		mapInfo.setLayout (properties.get("LAYOUT"));
		mapInfo.setNrows (Integer.valueOf(properties.get("NROWS")));
		mapInfo.setNcols (Integer.valueOf(properties.get("NCOLS")));
		mapInfo.setNbands (Integer.valueOf(properties.get("NBANDS")));
		mapInfo.setNbits (Integer.valueOf(properties.get("NBITS")));
		mapInfo.setBandrowbytes (Integer.valueOf(properties.get("BANDROWBYTES")));
		mapInfo.setTotalrowbytes (Integer.valueOf(properties.get("TOTALROWBYTES")));
		mapInfo.setBandgapbytes (Integer.valueOf(properties.get("BANDGAPBYTES")));
		mapInfo.setNodata (Integer.valueOf(properties.get("NODATA")));
		mapInfo.setUlxmap (Double.valueOf(properties.get("ULXMAP")));
		mapInfo.setUlymap (Double.valueOf(properties.get("ULYMAP")));
		mapInfo.setXdim (Double.valueOf(properties.get("XDIM")));
		mapInfo.setYdim (Double.valueOf(properties.get("YDIM")));
		
		return mapInfo;

	}

}
